/**
 * Created by Administrator on 2018/8/20.
 */
import axios from 'axios'
import router from '../router'
import {Loading} from 'element-ui'

let base = ''
let needLoadingRequestCount = 0
let showFullScreenLoading = function () {
  if (needLoadingRequestCount === 0) {
    startLoading()
  }
  needLoadingRequestCount++
}
let tryHideFullScreenLoading = function () {
  if (needLoadingRequestCount <= 0) {
    return
  }
  needLoadingRequestCount--
  if (needLoadingRequestCount === 0) {
    endLoading()
  }
}

let loading
let startLoading = function () {
  loading = Loading.service({
    lock: true,
    text: '加载中',
    spinner: 'el-icon-loading',
    background: 'rgba(0, 0, 0, 0.7)'
  })
}
let endLoading = function () {
  loading.close()
}

// 请求拦截器
axios.interceptors.request.use(function (config) {
  showFullScreenLoading()
  // config.headers.Authorization = `${Token}`
  return config
}, function (error) {
  return Promise.reject(error)
})

// 响应拦截器
axios.interceptors.response.use(function (response) {
  // 1001 定义为未登录的状态码
  if (response.data.status === 403) {
    router.push({
      path: '/Login'
    })
  }
  tryHideFullScreenLoading()
  return response
}, function (error) {
  // console.log(error);
  // if (error.response.status === 504 || error.response.status === 404) {
  //   alert('服务器错误')
  // } else if (error.response.status === 403) {
  //   alert('权限不足，请联系管理员')
  // } else {
  //   alert('位置错误')
  // }
  return Promise.reject(error)
})

// 封装axios的post请求
export function postRequest (url, params) {
  return axios({
    method: 'post',
    url: `${base}${url}`,
    data: params,
    transformRequest: [function (data) {
      let ret = ''
      for (let it in data) {
        ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
      }
      return ret
    }],
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded'
    }
  })
}

// 封装上传文件接口
export function uploadFileRequest (url, params) {
  return axios({
    method: 'post',
    url: `${base}${url}`,
    data: params,
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  })
}

// 封装put接口
export function putRequest (url, params) {
  return axios({
    method: 'put',
    url: `${base}${url}`,
    data: params,
    transformRequest: [function (data) {
      let ret = ''
      for (let it in data) {
        ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
      }
      return ret
    }],
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded'
    }
  })
}

// 封装删除接口
export function deleteRequest (url) {
  return axios({
    method: 'delete',
    url: `${base}${url}`
  })
}

// 封装get接口
export function getRequest (url) {
  return axios({
    method: 'get',
    url: `${base}${url}`
  })
}
